<template>
  <div class="user-list-container">
    <!-- 操作按钮区域 -->
    <div class="action-bar">
      <div class="left-actions">
        <el-button type="primary" icon="el-icon-plus" @click="handleAddUser">添加用户</el-button>
        <el-button type="info" icon="el-icon-refresh" @click="fetchUserList">刷新</el-button>
      </div>
      <div class="right-actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索用户名"
          prefix-icon="el-icon-search"
          clearable
          class="search-input"
          @clear="handleSearch"
          @keyup.enter.native="handleSearch"
        >
          <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
        </el-input>
      </div>
    </div>

    <!-- 用户列表表格 -->
    <el-card shadow="hover" class="table-card">
      <el-table
        :data="userList"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
        class="user-table"
        :show-header="true"
        :default-sort="{ prop: 'userId', order: 'ascending' }"
        :header-cell-style="{ backgroundColor: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column prop="userId" label="用户ID" width="180" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column prop="userName" label="用户名" width="120" align="center"></el-table-column>
        <el-table-column prop="phone" label="手机号" width="150" align="center"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="200" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column prop="roleId" label="角色" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="getRoleTagType(scope.row.roleId)" effect="dark">
              {{ getRoleName(scope.row.roleId) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="0"
              :inactive-value="1"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>

        <el-table-column prop="registerTime" label="注册时间" width="250" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.registerTime }}
          </template>
        </el-table-column>

        <el-table-column prop="loginTime" label="最后登录" width="250" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.loginTime ? scope.row.loginTime : '从未登录' }}
          </template>
        </el-table-column>

        <el-table-column label="操作"  width="180" align="center">
          <template slot-scope="scope">
            <el-button-group class="operation-btns">
              <el-tooltip content="编辑" placement="top">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleEditUser(scope.row)"></el-button>
              </el-tooltip>
              <el-tooltip content="查看详情" placement="top">
                <el-button type="info" size="mini" icon="el-icon-view" @click="handleViewUser(scope.row)"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleDeleteUser(scope.row)"></el-button>
              </el-tooltip>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          background
        ></el-pagination>
      </div>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" @close="resetForm" center>
      <el-form :model="userForm" :rules="rules" ref="userForm" label-width="100px" status-icon>
        <el-form-item label="用户名" prop="userName" v-if="isAddMode">
          <el-input v-model="userForm.userName" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="isAddMode">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword" v-if="isAddMode">
          <el-input v-model="userForm.confirmPassword" type="password" placeholder="请确认密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="userForm.roleId" placeholder="请选择角色" style="width: 100%">
            <el-option v-for="role in roleList" :key="role.roleId" :label="role.roleName" :value="role.roleId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio :label="0">启用</el-radio>
            <el-radio :label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 用户详情对话框 -->
    <el-dialog title="用户详情" :visible.sync="detailsVisible" width="600px" center>
      <el-descriptions class="user-details" :column="2" border>
        <el-descriptions-item label="用户名">{{ currentUser.userName }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ currentUser.phone }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ currentUser.email }}</el-descriptions-item>
        <el-descriptions-item label="角色">
          <el-tag :type="getRoleTagType(currentUser.roleId)">
            {{ getRoleName(currentUser.roleId) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentUser.status === 0 ? 'success' : 'danger'">
            {{ currentUser.status === 0 ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentUser.registerTime }}</el-descriptions-item>
        <el-descriptions-item label="最后登录">{{ currentUser.loginTime ? currentUser.loginTime : '从未登录' }}</el-descriptions-item>
      </el-descriptions>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailsVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import service from '@/utils/request';
import CryptoJS from 'crypto-js'  // 添加这行导入
export default {
  name: 'UserList',
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.userForm.confirmPassword !== '') {
          this.$refs.userForm.validateField('confirmPassword');
        }
        callback();
      }
    };
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.userForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };

    return {
      // 用户列表数据
      userList: [],
      loading: false,
      searchQuery: '',
      
      // 分页参数
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      
      // 选中的用户
      selectedUsers: [],
      
      // 角色列表数据
      roleList: [],
      
      // 对话框控制
      dialogVisible: false,
      detailsVisible: false,
      dialogTitle: '添加用户',
      isAddMode: true,
      
      // 当前编辑/查看的用户
      currentUser: {},
      
      // 表单数据
      userForm: {
        userId: '',
        userName: '',
        // email: '',
        password: '',
        confirmPassword: '',
        roleId: '', // 默认使用普通用户角色
        status: 0
      },
      
      // 表单验证规则
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        password: [
          { validator: validatePass, trigger: 'blur' }
        ],
        confirmPassword: [
          { validator: validatePass2, trigger: 'blur' }
        ],
        roleId  : [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      },
    };
  },
  computed: {
  },
  created() {
    this.fetchUserList();
    this.fetchRoleList();
  },
  methods: {
    // 获取角色列表
    fetchRoleList() {
      service.get('/api/system/role/getRoleLists').then(res => {
        if(res.code === 200){
          console.log(res);
          // 转换为特定格式
          this.roleList = (res.data || []).map(item => {
            return {
              roleId: item.roleId,
              roleName: item.roleName
            }
          });
          
          console.log(this.roleList);
        } else {
          this.$message.error(res.message || '获取角色列表失败');
        }
      }).catch(err => {
        this.$message.error(err.message || '获取角色列表失败');
      });
    },
    
    // 获取用户列表
    fetchUserList() {
      this.loading = true;

      service.get('/api/system/user/getUserList',{
        params:{
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
          userName: this.searchQuery
        }
      }).then(res => {
        if(res.code === 200){
          console.log(res);
          this.userList = res.data.list;
          this.pagination.total = res.data.total;
          this.loading = false;
        }
      }).catch(err => {
        this.$message.error(err.message);
        this.loading = false;
      });
    },
    
    // 处理搜索
    handleSearch() {
      this.pagination.currentPage = 1;
      this.fetchUserList();
    },
    
    // 处理选择变化
    handleSelectionChange(selection) {
      this.selectedUsers = selection;
    },
    
    // 处理添加用户
    handleAddUser() {
      this.dialogTitle = '添加用户';
      this.isAddMode = true;
      this.dialogVisible = true;
    },
    
    // 处理编辑用户
    handleEditUser(row) {
      this.dialogTitle = '编辑用户';
      this.isAddMode = false;
      this.userForm = { ...row };
      this.dialogVisible = true;
    },
    
    // 处理查看用户详情
    handleViewUser(row) {
      this.currentUser = row;
      this.detailsVisible = true;
    },
    
    // 处理删除用户
    handleDeleteUser(row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        service.delete(`/api/system/user/deleteUser/${row.userId}`).then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.fetchUserList();
          } else {
            this.$message.error(res.message || '删除失败');
          }
        }).catch(err => {
          this.$message.error(err.message || '删除失败');
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    
    // 处理状态变更
    handleStatusChange(row) {
      const statusText = row.status === 1 ? '禁用' : '启用';
      
      service.put('/api/system/user/changeStatus', {
       
          userId: row.userId,
          status: row.status
        
      }).then(res => {
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: `用户已${statusText}`
          });
        } else {
          // 如果API调用失败，恢复原状态
          row.status = row.status === 0 ? 1 : 0;
          this.$message.error(res.message || `${statusText}失败`);
        }
      }).catch(err => {
        // 如果API调用出错，恢复原状态
        row.status = row.status === 0 ? 1 : 0;
        this.$message.error(err.message || `${statusText}失败`);
      });
    },
    
    // 分页大小变化
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.fetchUserList();
    },
    
    // 页码变化
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.fetchUserList();
    },
    
    // 提交表单
    submitForm() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          // 根据是添加还是编辑模式执行不同操作
          if (this.isAddMode) {
            // 添加用户
            service.post('/api/system/user/addUser', {
              userName: this.userForm.userName,
              password: CryptoJS.MD5(this.userForm.password).toString(),
              roleId: this.userForm.roleId,
              status: this.userForm.status
            }).then(res => {
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: '添加用户成功!'
                });
                this.dialogVisible = false;
                this.fetchUserList();
              } else {
                this.$message.error(res.message || '添加用户失败');
              }
            }).catch(err => {
              this.$message.error(err.message || '添加用户失败');
            });
          } else {
            // 编辑用户
            service.put('/api/system/user/updateUser', {
              userId: this.userForm.userId,
              roleId: this.userForm.roleId,
              status: this.userForm.status,
              token: localStorage.getItem('token')
            }).then(res => {
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: '更新用户成功!'
                });
                this.dialogVisible = false;
                this.fetchUserList();
              } else {
                this.$message.error(res.message || '更新用户失败');
              }
            }).catch(err => {
              this.$message.error(err.message || '更新用户失败');
            });
          }
        } else {
          return false;
        }
      });
    },
    
    // 重置表单
    resetForm() {
      if (this.$refs.userForm) {
        this.$refs.userForm.resetFields();
      }
      this.userForm = {
        userId: '',
        userName: '',
        // email: '',
        password: '',
        confirmPassword: '',
        roleId:'2', // 默认使用普通用户角色
        status: 0
      };
    },
    // 根据roleId获取角色名称
    getRoleName(roleId) {
      console.log(roleId+"eeeeeeeeeeeeeeeeeeeeeeeeeeee");
      const role = this.roleList.find(role => role.roleId == roleId);
      console.log(role+"1111111");
      return role ? role.roleName : '未知角色';
    },
    // 获取角色标签类型
    getRoleTagType(roleId) {
      // 根据角色ID设置不同的标签类型
      if (roleId === 1) return 'danger';
      if (roleId === 2) return 'warning';
      return 'success';
    },
  }
};
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-actions {
  display: flex;
  gap: 10px;
}

.right-actions {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.table-card {
  margin-bottom: 20px;
}

.user-table {
  margin-bottom: 20px;
}

.operation-btns {
  display: inline-block;
}

.operation-btns .el-button {
  padding: 7px 12px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.user-details {
  width: 100%;
}

.delete-btn {
  color: #F56C6C;
}

.delete-btn:hover {
  color: #f78989;
}

/* Element UI 默认样式覆盖 */
.el-table th {
  background-color: #f5f7fa;
  color: #606266;
}

.el-table--striped .el-table__body tr.el-table__row--striped td {
  background: #fafafa;
}

.el-table--enable-row-hover .el-table__body tr:hover>td {
  background-color: #f5f7fa;
}
</style>
